<template>
    <div class="default-main">
        <el-dialog v-model="outerVisible" :close-on-click-modal="false" title="编辑" width="60%">
            <el-form :model="form" label-width="auto" style="max-width: 90%">
                <el-form-item label="应用名称">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="app_key">
                    <el-input v-model="form.app_key" />
                </el-form-item>
                <el-form-item label="app_secret">
                    <el-input type="textarea" :rows="3" v-model="form.app_secret" />
                </el-form-item>
                <el-form-item label="应用描述">
                    <el-input type="textarea" :rows="3" v-model="form.app_desc" />
                </el-form-item>
                <el-form-item label="应用状态">
                    <el-switch v-model="form.app_status" />
                </el-form-item>
                <el-scrollbar height="150px">
                    <el-tree
                        ref="treeRef"
                        style="max-width: 600px"
                        :data="data"
                        show-checkbox
                        default-expand-all
                        node-key="id"
                        highlight-current
                        :props="defaultProps"
                        :default-checked-keys="checkedKeys"
                    />
                </el-scrollbar>
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="outerVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveapp">
                    保存
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
            <template #action="{ row }">
                <vxe-button mode="text" status="primary" icon="vxe-icon-edit" @click="addAppAdminModal(row)">创建管理</vxe-button>
            </template>
        </vxe-grid>
        <vxe-modal
            resize
            destroy-on-close
            show-footer
            show-confirm-button
            show-cancel-button
            v-model="addAdminPopup"
            title="编辑"
            width="60vw"
            height="60vh"
            :loading="addAdminloading"
            @confirm="addAdminConfirmEvent">
            <vxe-form ref="addAdminFormRef" v-bind="addAdminformOptions"></vxe-form>
        </vxe-modal>
    </div>  
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { ElLoading,ElButton, ElDialog, ElForm } from 'element-plus';
import {callBackApi} from '../../../api'
import { ElTree,ElMessageBox } from 'element-plus'

const loading = ref(false);
const openLoading = () => {
    loading.value = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
const closeLoading = () => {
    loading.value.close()
}
const outerVisible = ref(false)
const form = reactive({
    id: null,
    name: '',
    app_key: '',
    app_secret: '',
    app_desc: '',
    app_status: true
})
const gridRef = ref({})
const data = ref([])
const treeRef = ref([])
const checkedKeys = ref([])
const defaultProps = {
  children: 'children',
  label: 'title',
}
const addAdminPopup = ref(false)
const addAdminloading = ref(false)
const addAdminformOptions = reactive({
  titleWidth: 80,
  titleAlign: 'right',
  titleColon: true,
  data: {
        app_id: null,
        username: '',
        username_show: '',
        password: '',
        email: '',
        remark: ''
    },
  rules: {
  },
  items: [
    { field: 'username', title: '用户名', span: 24, itemRender: { name: 'VxeInput' } },
    { field: 'username_show', title: '用户姓名', span: 24, itemRender: { name: 'VxeInput' } },
    { field: 'password', title: '密码', span: 24, itemRender: { name: 'VxeNumberInput' } },
  ]
})
const addAppAdminModal = (row) => {
    addAdminformOptions.data
    addAdminPopup.value = true
}
const addAdminConfirmEvent = async () => {
    addAdminloading.value = true
    let params = addAdminformOptions.data
    let res = await callBackApi(
        "base/addAppAdmin/",
        params,
        {loading:true},
        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
    )
    if (res.code === 200) {
        addAdminPopup.value = false
        addAdminloading.value = false
        ElMessageBox.alert('创建成功', '提示',{})
        initTableData()
    }else {
        addAdminloading.value = false
        ElMessageBox.alert(res.msg, '提示',{})
    }
}
const gridOptions = reactive({
    border: true,
    stripe: true,
    keepSource: true,
    size: 'small',
    height:'auto',
    customConfig: {
        placement: 'bottom-right',
        mode:'modal'
    },
    loading: false,
    toolbarConfig: {
        custom: true,
        buttons: [
            { name: '新增', code: 'add', status: 'primary' },
            { name: '删除', code: 'del', status: 'error' }
        ]
    },
    formConfig: {
        data: {
            name: ''
        },
        items: [
            { field: 'name', title: '应用名称', itemRender: { name: 'VxeInput' } },
            {
                itemRender: {
                name: 'VxeButtonGroup',
                options: [
                    { type: 'submit', content: '搜索', status: 'primary' },
                ]
                }
            }
        ]
    },
    pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 20,
        layouts: ['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']
    },
    checkboxConfig: {
        highlight: true
    },
    columns: [
        { type: 'checkbox', width: 40 },
        { type: 'seq', width: 70 },
        { field: 'name', title: '应用名称' },
        { field: 'app_key', title: 'app_key',showOverflow: 'ellipsis' },
        { field: 'app_secret', title: 'app_secret',showOverflow: 'ellipsis' },
        { field: 'app_desc', title: '应用描述' ,showOverflow: 'ellipsis'},
        { field: 'app_status', title: '应用状态' },
        { title: '操作', width: 100, slots: { default: 'action' } }
    ],
    data:[]
});

//清理表单数据
const clearForm = () => {
    form.id = null
    form.name = ''
    form.app_key = ''
    form.app_secret = ''
    form.app_desc = ''
    form.app_status = true
    checkedKeys.value = []
}

//初始化table数据
const initTableData = async () => {
    gridOptions.loading = true
    let params = {
        page: gridOptions.pagerConfig.currentPage,
        size: gridOptions.pagerConfig.pageSize,
        query:{
            name__contains: gridOptions.formConfig.data.name
        }
    }
    let res = await callBackApi(
        "base/appList/",
        params,
        {loading:false},
        {}
    )
    if (res.code === 200) {
        gridOptions.data = res.data
        gridOptions.pagerConfig.total = res.total
    }
    gridOptions.loading = false
}

const addAppAdmin = async (row) => {
    let res = await callBackApi(
        "base/addAppAdmin/",
        {app_id: row.id},
        {loading:true},
        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
    )
    if (res.code === 200) {
        ElMessageBox.alert('创建成功', '提示',{})
        initTableData()
    }else {
        ElMessageBox.alert(res.msg, '提示',{})
    }
}

const initreedata = async () => {
    let res = await callBackApi(
        "base/getPermissionTree/",
        null,
        {loading:true},
        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
    );
    if (res.code === 200) {
        data.value = res.data
    }
}
onMounted( async () => {
    await initTableData()
})
const gridEvents = {
    async toolbarButtonClick (params) {
        switch (params.code) {
            case 'add':
                openLoading()
                clearForm()
                initreedata()
                outerVisible.value = true
                closeLoading()
                break;
            case 'del':
                const $grid = gridRef.value
                if(!$grid){
                    ElMessageBox.alert('无数据', '提示',{})
                    return
                }
                let ids = $grid.getCheckboxRecords().map(item => item.id)
                if (ids.length === 0) {
                    ElMessageBox.alert('请选择要删除的行', '提示',{})
                    return
                }
                let confirm = await ElMessageBox.confirm('确认删除吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                if (confirm) {
                    let res = await callBackApi(
                        "base/deleteApp/",
                        {ids: ids},
                        {loading:true},
                        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
                    );
                    if (res.code === 200) {
                        ElMessageBox.alert('删除成功', '提示',{})
                        initTableData()
                    }
                }
                break;
            default:
                break;
        }
    },
    async cellDblclick ({ row }) {
        clearForm()
        await initreedata()
        let res = await callBackApi(
            "base/appDetail/",
            {id: row.id},
            {loading:true},
            {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
        )
        if (res.code === 200) {
            form.id = res.data.id
            form.name = res.data.name
            form.app_key = res.data.app_key
            form.app_secret = res.data.app_secret
            form.app_desc = res.data.app_desc
            form.app_status = res.data.app_status
            checkedKeys.value = res.data.permission_ids
            outerVisible.value = true
        }
    },
    async formSubmit () {
        await initTableData()
    },
    async pageChange ({ pageSize, currentPage }) {
        gridOptions.pagerConfig.currentPage = currentPage
        gridOptions.pagerConfig.pageSize = pageSize
        initTableData()
    }
}
const saveapp = async () => {
    let params = {
        app:{
            id: form.id,
            name: form.name,
            app_key: form.app_key,
            app_secret: form.app_secret,
            app_desc: form.app_desc,
            app_status: form.app_status
        },
        permission_ids: treeRef.value.getCheckedKeys()
    }
    let res = await callBackApi(
        "base/saveApp/",
        params,
        {loading:true},
        {lock: true,text: 'Loading',background: 'rgba(0, 0, 0, 0.7)'}
    );
    if (res.code === 200) {
        outerVisible.value = false
        initTableData()
        ElMessageBox.alert('保存成功', '提示',{})
    }else {
        ElMessageBox.alert(res.msg, '提示',{})
    }
    
}
</script>

<style scoped lang="scss">
.default-main {
    height: 96%;
}
</style>